import React, { Component } from 'react';
import DateUtil from '../../util/DateUtil';
import { commitReserveData, getPartyDetail,postUpdateReaderMessage } from '../../api/index';
import { RouteComponentProps } from 'react-router-dom';
import { Modal, Toast } from 'antd-mobile';
import Supplement from './supplement-message'
const prompt = Modal.prompt;
interface Props extends RouteComponentProps {
    match: any;
}

interface State {
    party: any;
    id: string;
    user: any;
    supplement:boolean
    supplementObject:{
        mobile:string,
        email:string
    }
}

class ReserveCommit extends Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            party: {},
            id: '',
            user: {},
            supplement:false,
            supplementObject:{
                mobile:'',
                email:''
            }
        };
    }
    componentDidMount() {
        const {
            match: {
                params: { id },
            },
            history: { push },
        } = this.props;
        let userJsonStr = sessionStorage.getItem('user') || '';
        if (!userJsonStr) {
            push('/login');
        }
        if (!!id && !!userJsonStr) {
            let partyJSONString = sessionStorage.getItem(id) || '';
            if (!!partyJSONString) {
                const party = JSON.parse(partyJSONString);
                let user = JSON.parse(userJsonStr);
                this.setState({
                    party,
                    id,
                    user,
                });
                return;
            }
        }

        push('/');
    }
    commitData = () => {
        const {
            match: {
                params: { id },
            },
            history: { push },
        } = this.props;
        let _ = this;
        let params = this.state.party;

        if (params.category === 1) {
            params['status'] = 1;
        } else if (params.category === 2) {
            params['status'] = 0;
        } else {
            params['status'] = 0;
        }
        params['reserveDate'] = new Date();
        params['quotaFlag'] = 'false';
        params['channel'] = 1;

        let user = this.state.user;
        let operator = user.personal
   
        if(!operator.mobilePhone){
            this.setState({supplement:true}) 
            return false;//补充联系信息
        }
       
        let readerReserveGroup = [
            {
                barcode: user.barcode,
                name: `${operator.firstName} ${operator.lastName}`,
                mobilePhone: operator.mobilePhone,
            },
        ];
 
        operator.username = `${operator.firstName} ${operator.lastName}`;
        delete operator.addresses;
        delete operator.preferredContactTypeId;
        delete operator.servicePoints;
        delete operator.curServicePoint;
        delete operator.dateOfBirth;
        let request = {
            channel: 2,
            partyId: params.id,
            status: params.status,
            quotaFlag: params.quotaFlag,
            readerReserveGroup,
            propertyName: params.propertyName,
            imageId: params.imageId,
            partyVenue: params.venue,
            partyStartDate: params.partyStartDate,
            partyEndDate: params.partyEndDate,
            partyCategory: params.category,
            notes: '',
            partyName: params.partyName,
            operator
        };
        //console.log(JSON.stringify(request))
        commitReserveData(request)
            .then((response: any) => {

                Toast.loading("正在报名中...", 3, () => {
                    const barcode = sessionStorage.getItem('barcode') || 'undefined';
                    const partyId: string = response.data.partyId;
                    getPartyDetail({ barcode, id: partyId }).then((re: any) => {
                        const { data: { webReserveStatus } } = re
                        if (!webReserveStatus.isReserve) {
                            Toast.success("目前报名人数较多,你已排队成功!", 2, () => {
                                push('/');
                            });
                        } else {
                            _.props.history.push(`/reserve_result/${params.id}`);
                        }
                    })
                })


            })
            .catch((e) => {
                Toast.fail(e,3);
                push('/');
            });
    };
 
    render() {
        return (
       <div>
        <Supplement modifySupplement={(values:{mobile:string,email:string})=>{
            if(!!values.mobile){
                let user = this.state.user;
                let operator = user.personal
                delete user.metadata
                operator.mobilePhone = values.mobile; 
                if(!!values.email) operator.email = values.email;
                user.personal = operator
                if(!! user.personal.username) delete  user.personal.username;
                sessionStorage.setItem('user',JSON.stringify(user));
                postUpdateReaderMessage(user).then((res)=>{
                    console.log("update success")
                }).catch(e=>{console.log(e)})
                this.setState({supplementObject:values,supplement:false,user},()=>{
                this.commitData()
            })
        }}} supplement={this.state.supplement} changeSupplement={()=>{
            this.setState((rep)=>{
               const supplement=!rep.supplement
               return {
                   supplement
               }
            })
        }} /> 
          <div className="padding-lr20">
                    <div className="act-center-top ">
                        <div className="act-center-title margin-b40">{this.state.party.partyName} </div>
                        <p>
                            报名时间:
                            <span>
                                {`${DateUtil.mergeFormat(
                                    this.state.party.reserveStartDate,
                                    this.state.party.reserveEndDate
                                )} `}
                            </span>
                        </p>
                        <p>
                            签到时间:
                            <span>
                                {`${DateUtil.mergeFormat(
                                    this.state.party.attendStartDate,
                                    this.state.party.attendEndDate
                                )} `}
                            </span>
                        </p>
                        <p>
                            活动时间:
                            <span>
                                {`${DateUtil.mergeFormat(
                                    this.state.party.partyStartDate,
                                    this.state.party.partyEndDate
                                )} `}
                            </span>
                        </p>
                        <p>
                            活动地点:<span> {this.state.party.venue}</span>
                        </p>
                    </div>

                    <div className="act-center-top">
                        <div className="act-center-title">温馨提示</div>

                        <p>
                            报名登记之后，如不能按时参加，请进“个人中心”-“我的活动”栏目，在可以取消的时间内取消报名，或者在可请假的时间内请假，否则视为违约。
                        </p>
                    </div>
                </div>

                <div
                    className="act-center-btn"
                    onClick={() => {
                        this.commitData();
                    }}>
                    确定
                </div>
            </div>
        );
    }
}

export default ReserveCommit;
